/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-2-20
 * 
**/
package com.julewa.freemarker;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class FreemarkerManager { 
	private Configuration config = new Configuration();
	private Map<String, Template> templates = new HashMap<String, Template>();
	public FreemarkerManager(String path){
		config.setDefaultEncoding("UTF-8");
		config.setOutputEncoding("UTF-8");
		config.setNumberFormat("#");
		config.setWhitespaceStripping(false);
		config.setObjectWrapper(new FreemarkerObjectWrapper());
		config.setClassForTemplateLoading(this.getClass(), path);
		//
	}
	
	public FreemarkerManager(Class<?> clazz){
		this(clazz, null);
	}
	
	public FreemarkerManager(Class<?> clazz, String path){
		this("/" + clazz.getPackage().getName().replace('.', '/') + ((path == null)?"":("/" + path)));
	}
	
	public FreemarkerBuilder load(String name){
		try {
			Template template = templates.get(name);
			if(template == null){
				template = config.getTemplate(name + ".ftl");
				templates.put(name, template);
			};
			return new FreemarkerBuilder(template);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private class FreemarkerObjectWrapper implements ObjectWrapper{
		private ObjectWrapper wrapper = ObjectWrapper.DEFAULT_WRAPPER;
		private TemplateModel BLANK;
		{try {
				BLANK = wrapper.wrap("");
			} catch (TemplateModelException e) {
				e.printStackTrace();
			}
		}
		@Override
		public TemplateModel wrap(Object obj) throws TemplateModelException {
			if(obj == null)return BLANK;
			return wrapper.wrap(obj);
		}

	}

}
